package commentDao;

import java.util.ArrayList;
import java.util.List;

import topicDao.TopicEntity;

import java.sql.*;

import usersDao.DBUtils;

public class MySqlCommentDao implements CommentDAO {

	@Override
	public int add(CommentEntity c) {
		String sql = "insert into `comments`(cid,cnid,ccontent,cdate,cip,cauthor) values (null,?,?,?,?,?)";
		return DBUtils.executeUpdate(sql, c.getCnid(), c.getCcontent(),
				c.getCdate(), c.getCip(), c.getCauthor());
	}

	@Override
	public List<CommentEntity> findComments(long newsid) {
		List<CommentEntity> list = new ArrayList<CommentEntity>();
		CommentEntity c = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		String sql = "select * from `comments` where cnid = ?";
		Connection conn = null;
		try {
			conn = DBUtils.getConnection();
			st = conn.prepareStatement(sql);
			st.setLong(1, newsid);
			rs = st.executeQuery();
			while (rs.next()) {
				c = new CommentEntity();
				c.setCid(rs.getInt("cid"));
				c.setCnid(rs.getInt("cnid"));
				c.setCcontent(rs.getString("ccontent"));
				c.setCdate(rs.getDate("cdate"));
				c.setCip(rs.getString("cip"));
				c.setCauthor(rs.getString("cauthor"));
				list.add(c);
			}
		} catch (SQLException ex) {
			ex.printStackTrace();
		} finally {
			DBUtils.close(rs, st, conn);
		}
		return list;
	}

	@Override
	public int del(long cid) {
		String sql="delete from `comments` where cid=?";
		return DBUtils.executeUpdate(sql, cid);
	}

	@Override
	public int update(CommentEntity c) {
		String sql="update  `comments` set cnid=?,ccontent=?,cdate=?,cip=?,cauthor=? where cid=?";
		return DBUtils.executeUpdate(sql, c.getCnid(),c.getCcontent(),c.getCdate(),c.getCip(),c.getCauthor(),c.getCid());
	}


	
}
